package util;
import java.util.ArrayList;
import java.util.Iterator;


public class Prob<E> {
	ArrayList<Probability<E>> probabilities;
	
	public Prob(){
		probabilities = new ArrayList<Probability<E>>();
	}
	
	public void add(Probability<E> prob){
		probabilities.add(prob);
	}
	public void add(E val, float weight){
		probabilities.add(new Probability<E>(val, weight));
	}
	
	public float totalWeight(){
		Iterator<Probability<E>> it = probabilities.iterator();
		float weight = 0;
		while(it.hasNext()){
			weight = it.next().weight;
		}
		
		return weight;
	}
	
	public E choose(){
		float rnd = (float)Math.random() * totalWeight();
		Iterator<Probability<E>> it = probabilities.iterator();
		if(!it.hasNext()) return null;
		
		
		Probability<E> prob = it.next();
		float cumulativeWeight = prob.weight;
		
		while(it.hasNext() && cumulativeWeight < rnd){
			prob = it.next();
			cumulativeWeight += prob.weight;
			
		}
		return prob.getValue();
	}
	
	
	
}

